import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 登录状态
    isLoggedIn: false,
    // 用户信息
    userInfo: null,
    // token
    token: null
  },
  
  mutations: {
    // 设置登录状态
    SET_LOGIN_STATUS(state, status) {
      state.isLoggedIn = status;
    },
    
    // 设置用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo;
    },
    
    // 设置token
    SET_TOKEN(state, token) {
      state.token = token;
    },
    
    // 清除登录信息
    CLEAR_LOGIN_INFO(state) {
      state.isLoggedIn = false;
      state.userInfo = null;
      state.token = null;
    }
  },
  
  actions: {
    // 初始化登录状态
    initLoginStatus({ commit }) {
      const token = localStorage.getItem('token');
      const userInfo = localStorage.getItem('userInfo');
      
      if (token && userInfo) {
        commit('SET_TOKEN', token);
        commit('SET_USER_INFO', JSON.parse(userInfo));
        commit('SET_LOGIN_STATUS', true);
      }
    },
    
    // 登录
    login({ commit }, { token, userInfo }) {
      commit('SET_TOKEN', token);
      commit('SET_USER_INFO', userInfo);
      commit('SET_LOGIN_STATUS', true);
      
      // 保存到localStorage
      localStorage.setItem('token', token);
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
    },
    
    // 登出
    logout({ commit }) {
      commit('CLEAR_LOGIN_INFO');
      
      // 清除localStorage
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
    }
  },
  
  getters: {
    // 是否已登录
    isLoggedIn: state => state.isLoggedIn,
    
    // 获取用户信息
    userInfo: state => state.userInfo,
    
    // 获取token
    token: state => state.token,
    
    // 获取用户名
    username: state => state.userInfo ? state.userInfo.username : ''
  }
})
